package com.wen.sms.service.impl;

import com.wen.commonutils.GuLiUtils;
import com.wen.commonutils.HttpUtils;
import com.wen.servicebase.exception.BusinessException;
import com.wen.sms.service.SmsService;
import com.wen.sms.util.SmsProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：Win
 * @Date: 2021/6/13 22:51
 * @Description:
 */
@Service
public class SmsServiceImpl implements SmsService {
    /**
     * 发送短音验证服务
     *
     * @param mobile 目标手机
     * @return 验证码
     */
    @Override
    public String sendMessage(String mobile) {
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + SmsProperties.APPCODE);
//        服务端生成验证码(6位随机数)
        String code = GuLiUtils.getSixBitRandom();
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", mobile);
        querys.put("param", "code:" + code);
        querys.put("tpl_id", SmsProperties.TPL_ID);
        Map<String, String> bodys = new HashMap<>();

        try {
            HttpUtils.doPost(SmsProperties.HOST, SmsProperties.PATH, SmsProperties.METHOD, headers, querys, bodys);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("短信发送失败");
        }
    }
}
